package com.ship.contract.service.impl;

import com.ship.common.business.service.impl.BaseServiceImpl;
import com.ship.common.core.base.Export;
import com.ship.common.core.task.ExportTask;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.contract.mapper.ExportMapper;
import com.ship.contract.service.ExportService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author tangshixuan
 * @date 2023-9-6
 */
@Service
public class ExportServiceImpl extends BaseServiceImpl<ExportMapper, Export> implements ExportService {

    @Autowired
    private ExecutorService executorService;

    @Override
    public void finish(Long exportId, File file, String path) {
        Export export = super.getById(exportId);
        export.setStatus(1);
        export.setFilePath(path);
        export.setDealDate(new Date());
        export.setDealSeconds(new Long((System.currentTimeMillis() - export.getCreateDate().getTime()) / 1000).intValue());
        String fileSize = null;
        long length = file.length();
        if(length < 1024) {
            fileSize = length + "B";
        }else if(length < 1024 * 1024) {
            fileSize = length / 1024 + "KB";
        }else if(length < 1024 * 1024 * 1024) {
            fileSize = length / 1024 / 1024 + "MB";
        }else if(length < 1024 * 1024 * 1024 * 1024) {
            fileSize = length / 1024 / 1024 / 1024 + "GB";
        }
        export.setFileSize(fileSize);
        super.updateById(export);
    }

    @Override
    public void export(ExportTask exportTask) {
        Export export = new Export(exportTask.getDownloadFileName(),Long .valueOf(SecurityUtils.getStringUserId()));
        super.save(export);
        exportTask.setExportId(export.getId());
        executorService.execute(exportTask);
    }

}
